﻿using JV.Com.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;

namespace JV.Com.Business
{
    internal static class InternalService
    {
        internal static async Task<Dictionary<int, Machine>> GetMachines()
        {
            try
            {
                var machines = new Dictionary<int, Machine>();

                var result = await Downloader.Instance.DownloadStringAsync(RequestUrl.Get(RequestType.GetMachines));
                var flux = Tools.GetXmlRoot(result);

                foreach (var node in flux.ChildNodes)
                {
                    if (node is XmlElement && node.NodeName == "machine")
                    {
                        var element = (XmlElement)node;

                        var machine = new Machine();
                        machine.Id = int.Parse(element.GetValueOfElementAndCData("id"));
                        machine.Name = element.GetValueOfElementAndCData("nom");
                        machine.ShortName = element.GetValueOfElementAndCData("nom_court");
                        machine.Rank = int.Parse(element.GetValueOfElementAndCData("rang"));
                        machine.Color = element.GetValueOfElementAndCData("couleur");
                        machine.IsOld = element.GetValueOfElementAndCData("oldies") == "1";
                        machine.ImageUrl = element.GetValueOfElement("url_icone");
                        machines.Add(machine.Id, machine);
                    }
                }

                await Task.WhenAll(
                    machines.Values.Select(m => 
                        Task.Run(async () => m.Image = await Downloader.Instance.DownloadBytesAsync(m.ImageUrl))
                        )
                    );

                return machines;
            }
            catch
            {
                // TODO ?
                throw;
            }
        }
    }
}
